package xworker.swt.app.view.swt.widgets;

import org.eclipse.swt.widgets.*;
import org.xmeta.ActionContext;
import org.xmeta.Thing;
import org.xmeta.World;
import org.xmeta.annotation.ActionField;
import org.xmeta.util.ThingLoader;
import org.xmeta.util.UtilMap;
import xworker.dataObject.DataStore;
import xworker.dataObject.PageInfo;
import xworker.swt.dataObject.datastore.PagingToolbarDataStoreListener;
import xworker.swt.util.SwtUtils;
import xworker.swt.util.ThingCompositeCreator;

public class PagingToolbar {
	@ActionField
	public ActionContext actionContext;
	@ActionField
	public org.eclipse.swt.widgets.Composite afLabelComposite;
	@ActionField
	public org.eclipse.swt.widgets.ToolItem afterPageItem;
	@ActionField
	public org.eclipse.swt.widgets.Label afterPageLabel;
	@ActionField
	public org.eclipse.swt.widgets.ToolItem beforePageItem;
	@ActionField
	public org.eclipse.swt.widgets.Label beforePageLabel;
	@ActionField
	public org.eclipse.swt.widgets.Composite bfLabelComposite;
	@ActionField
	public org.eclipse.swt.layout.RowLayout dfLaelRowLayout;
	@ActionField
	public xworker.swt.events.SwtListener firstPageItemSelect;
	@ActionField
	public org.eclipse.swt.widgets.ToolItem firtPageItem;
	@ActionField
	public org.eclipse.swt.widgets.Label infoLabel;
	@ActionField
	public org.eclipse.swt.widgets.ToolItem lastPageItem;
	@ActionField
	public org.eclipse.swt.widgets.ToolItem nextPageItem;
	@ActionField
	public org.eclipse.swt.widgets.Text pageText;
	@ActionField
	public org.eclipse.swt.widgets.ToolItem prePgaeItem;
	@ActionField
	public org.eclipse.swt.widgets.ToolItem refresItem;
	@ActionField
	public org.eclipse.swt.widgets.ToolItem pageTextItem;
	@ActionField
	public org.eclipse.swt.widgets.Composite pagingComposite;

	Thing pageToolbar;
	DataStore dataStore;

	public PagingToolbar(Thing pageToolbar){
		this.pageToolbar = pageToolbar;
	}

	public void setValues(long totalCount, long totalPage, long currentPage, long start, long limit, long offset){
		if(currentPage > 1){
			firtPageItem.setEnabled(true);
			prePgaeItem.setEnabled(true);
		}else{
			firtPageItem.setEnabled(false);
			prePgaeItem.setEnabled(false);
		}
		if(totalPage > 1){
			pageTextItem.setEnabled(true);
			pageText.setText("" + currentPage);
		}else{
			pageTextItem.setEnabled(false);
			pageText.setText("1");
		}
		if(currentPage < totalPage){
			nextPageItem.setEnabled(true);
			lastPageItem.setEnabled(true);
		}else{
			nextPageItem.setEnabled(false);
			lastPageItem.setEnabled(false);
		}
		refresItem.setEnabled(true);

		String afterPageText = pageToolbar.doAction("getAfterPageText", actionContext);
		if(afterPageText != null && !"".equals(afterPageText)){
			afterPageLabel.setText(afterPageText.replace("{0}", "" + totalPage));
			afterPageLabel.pack();
			afterPageItem.setWidth(afterPageLabel.getSize().x + 5);
		}
		if(totalCount == 0 ){
			String emptyMsg = pageToolbar.doAction("getEmptyMsg", actionContext);
			if(emptyMsg != null && pageToolbar.getBoolean("displayInfo")){
				infoLabel.setText(emptyMsg);
				pagingComposite.layout();
			}else{
				infoLabel.setText("");
			}
		}else{
			String displayMsg = pageToolbar.doAction("getDisplayMsg", actionContext);
			if(displayMsg != null && pageToolbar.getBoolean("displayInfo")){
				String msg = displayMsg.replace("{0}", "" + (start + 1));
				msg = msg.replace("{1}", "" + (offset + 1));
				msg = msg.replace("{2}", "" + totalCount);
				infoLabel.setText(msg);
				pagingComposite.layout();
			}else{
				infoLabel.setText("");
			}
		}
		pageToolbar.put("currentPage", currentPage);
		pageToolbar.put("totalPage", totalPage);
		pageToolbar.put("start", start - 1);
		pageToolbar.put("totalCount", totalCount);
		pageToolbar.put("offset", offset);
		pageToolbar.put("limit", limit);

	}

	public DataStore getDataStore() {
		return dataStore;
	}

	public void setDataStore(DataStore dataStore) {
		this.dataStore = dataStore;
	}

	public static PagingToolbar getPagingToolbar(Thing thing){
		return (PagingToolbar) thing.get("pagingToolbar");
	}

	public static Object create(ActionContext actionContext){
		Thing self = (Thing) actionContext.get("self");
		//Control parent = (Control) actionContext.get("parent");
		World world = World.getInstance();		

		//创建PageToolbar
		/*ActionContext ac = new ActionContext();
		ac.put("parent", parent);
		ac.put("parentActionContext", actionContext);*/
		
		Thing compositeThing = world.getThing("xworker.swt.app.view.swt.widgets.PagingToolbar/@pagingComposite");
		ThingCompositeCreator creator = SwtUtils.createCompositeCreator(self, actionContext);
		creator.setCompositeThing(compositeThing);
		Composite composite = creator.create();
		ActionContext ac = creator.getNewActionContext();
		
		//Composite composite = (Composite) compositeThing.doAction("create", ac);
		ToolItem beforePageItem = (ToolItem) ac.get("beforePageItem");
		ToolItem afterPageItem = (ToolItem) ac.get("afterPageItem");		
		Label beforePageLabel = (Label) ac.get("beforePageLabel");
		Label afterPageLabel = (Label) ac.get("afterPageLabel");
		Label infoLabel = (Label) ac.get("infoLabel");
		
		//设置文本
		setToolTip(self, "firstText", ac.get("firtPageItem"), self.doAction("getFirstText", actionContext));
		setToolTip(self, "prevText", ac.get("prePgaeItem"), self.doAction("getPrevText", actionContext));
		setToolTip(self, "nextText", ac.get("nextPageItem"), self.doAction("getNextText", actionContext));
		setToolTip(self, "lastText", ac.get("lastPageItem"), self.doAction("getLastText", actionContext));
		setToolTip(self, "refreshText", ac.get("refresItem"), self.doAction("getRefreshText", actionContext));
		String beforePageText = self.doAction("getBeforePageText", actionContext);
		if(beforePageText != null){
		    beforePageLabel.setText(beforePageText);
		    beforePageLabel.pack();
		    beforePageItem.setWidth(beforePageLabel.getSize().x + 5);
		}
		String afterPageTextStr = self.doAction("getAfterPageText", actionContext);
		if(afterPageTextStr != null){
		    afterPageLabel.setText(afterPageTextStr.replace("{0}", "0"));
		    afterPageLabel.pack();
		    afterPageItem.setWidth(afterPageLabel.getSize().x + 5);
		}
		String emptyMsg = self.doAction("getEmptyMsg", actionContext);
		if(emptyMsg != null && self.getBoolean("displayInfo")){
		    infoLabel.setText(emptyMsg);
		}

		/*
		Bindings bindings = ac.push(null);
		bindings.put("parent", composite);
		try{
		    for(Thing child : self.getChilds()){
		        child.doAction("create", ac);
		    }
		}finally{
		    ac.pop();
		}*/

		//创建PageToolbar事物
		Thing pageToolbar = new Thing("xworker.swt.app.view.swt.widgets.PagingToolbar");
		pageToolbar.getAttributes().putAll(self.getAttributes());
		pageToolbar.set("extends", self.getMetadata().getPath());
		pageToolbar.set("context", ac);
		pageToolbar.put("composite", composite);
		ac.put("pageToolbar", pageToolbar);

		PagingToolbar pagingToolbar = new PagingToolbar(pageToolbar);
		ThingLoader.load(pagingToolbar, ac);
		pageToolbar.set("pagingToolbar", pagingToolbar);

		//和DataStore绑定
		String storeStr = self.getStringBlankAsNull("store");
		if(storeStr != null){
		    Object store = actionContext.get(storeStr);
		    if(store instanceof Thing){
		    	//旧版不建议使用的DataStore，保持兼容
		        pageToolbar.put("store", store);
		        pageToolbar.doAction("setStore", ac, UtilMap.toMap("store", store));
		    }else if(store instanceof DataStore){
		    	new PagingToolbarDataStoreListener(pagingToolbar, (DataStore) store, actionContext);
		    	//pagingToolbar.setDataStore((DataStore) store);
			}
		}

		actionContext.getScope(0).put(self.getMetadata().getName(), pageToolbar);
		return composite;
	}
	
	public static Object getControl(ActionContext actionContext) {
		Thing self = actionContext.getObject("self");
		return self.get("composite");
	}
	
	public static void setToolTip(Thing pageToolbar, String name, Object item, String tip){
	    //String tip = pageToolbar.getString(name);
	    if(tip != null && tip != ""){
	    	if(item instanceof Control){
	    		((Control) item).setToolTipText(tip);
	    	}else if(item instanceof ToolItem){
	    		((ToolItem) item).setToolTipText(tip);
	    	}
	    }
	}
	
	public static void setStore(ActionContext actionContext){
		Thing self = (Thing) actionContext.get("self");
		Thing store = (Thing) actionContext.get("store");
		
		//添加一个表格数据仓库监听
		Thing listener = new Thing("xworker.swt.app.view.swt.data.events.PageToolbarDataStoreListener");
		listener.put("pageToolbar", self);
		listener.put("store", store);

		//先调用监听初始化
		listener.doAction("onReconfig", actionContext, UtilMap.toMap("store", self));

		//加入到监听器中
		self.put("store",store);
		store.doAction("addListener", actionContext, UtilMap.toMap("listener", listener));

		//把监听和自身添加到table中以备后用
		self.set("storeListener", listener);
	}

	private static void reload(DataStore dataStore, Thing store, ActionContext actionContext){
		if(dataStore != null){
			dataStore.reload();
		}else if(store != null){
			store.doAction("reload", actionContext);
		}
	}
	public static void handleEvent(ActionContext actionContext){
		Event event = (Event) actionContext.get("event");
		Thing pageToolbar = (Thing) actionContext.get("pageToolbar");
		ActionContext parentActionContext = (ActionContext) actionContext.get("parentActionContext");
		ToolItem refresItem = (ToolItem) actionContext.get("refresItem");
		ToolItem firtPageItem = (ToolItem) actionContext.get("firtPageItem");
		ToolItem prePgaeItem = (ToolItem) actionContext.get("prePgaeItem");
		ToolItem nextPageItem = (ToolItem) actionContext.get("nextPageItem");
		ToolItem lastPageItem = (ToolItem) actionContext.get("lastPageItem");
		Text pageText = (Text) actionContext.get("pageText");		

		PagingToolbar pagingToolbar = PagingToolbar.getPagingToolbar(pageToolbar);
		DataStore dataStore = pagingToolbar.getDataStore();
		Thing store = dataStore == null ? (Thing) pageToolbar.get("store") : null;
		if(event.widget == refresItem){
			reload(dataStore, store, parentActionContext);
			return;
		}
		PageInfo pageInfo = null;
		if(dataStore != null){
			pageInfo = dataStore.getPageInfo();
		}else if(store != null){
			pageInfo = PageInfo.getPageInfo(store.get("pageInfo"));
		}
		if(pageInfo == null){
			return;
		}

		if(event.widget == firtPageItem){
		    pageInfo.setStart(0);
			reload(dataStore, store, parentActionContext);
		}else if(event.widget == prePgaeItem){
		    int page = pageToolbar.getInt("currentPage") - 1;
		    if(page < 1){
		        page = 1;
		    }
		    int start = (page - 1) * pageToolbar.getInt("limit");
		    if(start <= 0){
		        start = 0;
		    }
		    pageInfo.setStart(start);
			reload(dataStore, store, parentActionContext);
		}else if(event.widget == pageText){
		    int page = Integer.parseInt(pageText.getText());
		    if(page < 1){
		        page = 1;
		    }
		    int start = (page - 1) * pageToolbar.getInt("limit");
		    if(start <= 0){
		        start = 0;
		    }
		    pageInfo.setStart(start);
			reload(dataStore, store, parentActionContext);
		}else if(event.widget == nextPageItem){
		    int page = pageToolbar.getInt("currentPage") + 1;
		    if(page < 1){
		        page = 1;
		    }
		    int start = (page - 1) * pageToolbar.getInt("limit");
		    if(start <= 0){
		        start = 0;
		    }
		    pageInfo.setStart(start);
			reload(dataStore, store, parentActionContext);
		}else if(event.widget == lastPageItem){
		    int page = pageToolbar.getInt("totalPage");
		    if(page < 1){
		        page = 1;
		    }
		    int start = (page - 1) * pageToolbar.getInt("limit");
		    if(start <= 0){
		        start = 0;
		    }
		    pageInfo.setStart(start);
			reload(dataStore, store, parentActionContext);
		}
	}
}
